package com.cnb.telepathytalk.fragment;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.cnb.telepathytalk.R;
import com.cnb.telepathytalk.TelepathyTalkApplication;
import com.cnb.telepathytalk.adapter.NoticeListAdapter;
import com.cnb.telepathytalk.adapter.NoticeListAdapter.Holder;
import com.cnb.telepathytalk.dto.NoticeDTO;
import com.cnb.telepathytalk.util.NoticeParser;

public class NoticeFragment extends Fragment implements OnItemClickListener {
	private Context mContext;

	private ListView listView;
	private NoticeListAdapter adapter;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mContext = activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		adapter = new NoticeListAdapter(mContext);
		new NoticeLoadingTask().execute();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		final View view = inflater.inflate(R.layout.fragment_list, null);
		((TextView) view.findViewById(R.id.titlebarText)).setText(R.string.title_notice);
		view.setBackgroundColor(0xffffffff);

		listView = (ListView) view.findViewById(R.id.listView1);
		listView.setDividerHeight(0);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(this);

		return view;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		NoticeListAdapter.Holder holder = (Holder) arg1.getTag();
		boolean isSeleted = adapter.getItem(arg2).isShown();

		adapter.getItem(arg2).setShown(!isSeleted);
		holder.getBottomLayout().setVisibility(isSeleted ? View.GONE : View.VISIBLE);
		holder.getArrow().setSelected(!isSeleted);
	}

	private class NoticeLoadingTask extends AsyncTask<Void, Void, ArrayList<NoticeDTO>> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			TelepathyTalkApplication.showProgressDialog(mContext, R.string.wait);
		}

		@Override
		protected ArrayList<NoticeDTO> doInBackground(Void... params) {
			return new NoticeParser().parsingData();
		}

		@Override
		protected void onPostExecute(ArrayList<NoticeDTO> result) {
			super.onPostExecute(result);
			TelepathyTalkApplication.dismissProgressDialog();
			adapter.getList().addAll(result);
			adapter.notifyDataSetChanged();
		}
	}
}
